package com.jianchi.fsp.appui;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.etiennelawlor.imagegallery.library.activities.FullScreenImageGalleryActivity;
import com.etiennelawlor.imagegallery.library.activities.ImageGalleryActivity;
import com.etiennelawlor.imagegallery.library.adapters.FullScreenImageGalleryAdapter;
import com.etiennelawlor.imagegallery.library.adapters.ImageGalleryAdapter;
import com.squareup.picasso.Picasso;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, ImageGalleryAdapter.ImageThumbnailLoader, FullScreenImageGalleryAdapter.FullScreenImageLoader{

    HistoryManager hm;
    boolean isStartByAppName = false;
    HistoryAdapter hadp;
    String[] appNames;

    HashMap<String, ArrayList<String>> appDic = new HashMap<>();
    HashMap<String, ArrayList<String>> tagDic = new HashMap<>();

    @Override
    protected void onRestart() {
        super.onRestart();
        if(isStartByAppName){
            hadp.notifyDataSetChanged();
            isStartByAppName = false;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        toolbar.setLogo(R.mipmap.ic_launcher);

        ImageGalleryActivity.setImageThumbnailLoader(this);
        FullScreenImageGalleryActivity.setFullScreenImageLoader(this);


        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);


        initData();

        Menu menu = navigationView.getMenu();

        menu.clear();
        for (String k : tagDic.keySet())
            menu.add(k);

        Set<String> set = appDic.keySet();
        appNames = set.toArray(new String[set.size()]);
        // 创建一个ArrayAdapter封装数组
        ArrayAdapter<String> av = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, appNames);
        AutoCompleteTextView auto = (AutoCompleteTextView) findViewById(R.id.searchText);
        auto.setAdapter(av);

        TextView search_button = (TextView) findViewById(R.id.search_button);
        search_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean found = false;
                String appName = "";
                AutoCompleteTextView auto = (AutoCompleteTextView) findViewById(R.id.searchText);
                appName = auto.getText().toString().trim();

                if (!appDic.containsKey(appName)) {
                    if(!appName.isEmpty()) {
                        for (String s : appNames) {
                            if (s.indexOf(appName) >= 0) {
                                appName = s;
                                found = true;
                            }
                        }
                    }
                } else {
                    found = true;
                }
                if (found) {
                    hm.addHistory(appName, appDic.get(appName).get(0));
                    isStartByAppName = true;
                    startAppGallery(appName);
                } else {
                    Toast.makeText(getApplicationContext(), "找不到App", Toast.LENGTH_SHORT).show();
                }
            }
        });

        hm = new HistoryManager(getApplicationContext());
        hadp = new HistoryAdapter(hm.histories, getApplicationContext());

        ListView lv = (ListView) findViewById(R.id.listView);//得到ListView对象的引用 /*为ListView设置Adapter来绑定数据*/
        lv.setAdapter(hadp);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                History h = (History) view.getTag();
                startAppGallery(h.appName);
            }
        });


        APPUIApplication app = (APPUIApplication) getApplication(); // 获得CustomApplication对象
        app.appDic=appDic;
        app.tagDic=tagDic;
        app.hm=hm;
    }

    private void startAppGallery(String appName){
        Intent intent = new Intent(MainActivity.this, ImageGalleryActivity.class);

        intent.putStringArrayListExtra("images", appDic.get(appName));
        intent.putExtra("title", appName);

        startActivity(intent);
    }

    private void startTagGallery(String tagName){

        isStartByAppName = false;
        Intent intent = new Intent(MainActivity.this, ImageGalleryActivity.class);

        intent.putStringArrayListExtra("images", tagDic.get(tagName));
        intent.putExtra("title", tagName);

        startActivity(intent);
    }

    // 读取raw文件
    private void initData() {
        try {
            InputStream is = getResources().openRawResource(R.raw.content);
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));

            String line = null;
            while ((line = br.readLine()) != null) {
                //108天:2015/04/201504309119_2558.png,启动页;2015/04/201504306720_7371.png,搜索;2015/04/201504303417_1703.png,错误提示;2015/04/201504304799_7478.png,登录;2015/04/201504305222_6761.png,注册;2015/04/201504308171_637.png,列表;2015/04/201504306230_3916.png,菜单;2015/04/201504308115_5144.png,用户中心;
                int mi = line.indexOf(":");
                String appName = line.substring(0, mi);
                if(!appName.isEmpty()) {


                    if (!appDic.containsKey(appName))
                        appDic.put(appName, new ArrayList<String>());

                    String content = line.substring(mi + 1);
                    String[] cs = content.split(";");
                    for (String c : cs) {
                        String[] ss = c.split(",");
                        String cc = "http://www.apkui.com/zb_users/upload/" + ss[0];
                        appDic.get(appName).add(cc);
                        String tagName = ss[1];
                        if (!tagDic.containsKey(tagName))
                            tagDic.put(tagName, new ArrayList<String>());
                        tagDic.get(tagName).add(cc);
                    }
                }
            }

            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.

        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        if(id==R.id.action_allApp){
            Intent intent = new Intent(MainActivity.this, AllAppActivity.class);
            startActivity(intent);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        //int id = item.getItemId();

        String tagName = item.getTitle().toString();
        startTagGallery(tagName);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void loadFullScreenImage(ImageView iv, String imageUrl, int width, LinearLayout bglinearLayout) {
        if (imageUrl!=null && !imageUrl.isEmpty()) {
            Picasso.with(iv.getContext())
                    .load(imageUrl)
                    .resize(width, 0)
                    .into(iv);
        } else {
            iv.setImageDrawable(null);
        }
    }

    @Override
    public void loadImageThumbnail(ImageView iv, String imageUrl, int dimension) {
        if (imageUrl!=null && !imageUrl.isEmpty()) {
            Picasso.with(iv.getContext())
                    .load(imageUrl)
                    .resize(dimension, dimension)
                    .centerCrop()
                    .into(iv);
        } else {
            iv.setImageDrawable(null);
        }
    }
}
